package cmd

import (
	"context"
	"github.com/sirupsen/logrus"
	"time"
)

var (
	httpServerStopped chan bool
	gracefullyStop    uint32
	gracefullyStopCh  chan bool

//	TODO...
)

func init() {
	httpServerStopped = make(chan bool, 1)
	gracefullyStop = 0
	gracefullyStopCh = make(chan bool, 1)
}

func stop() error {
	//停止http服务
	err = stopHttpServer()
	if err != nil {
		return err
	}
	return nil
}

// 停止http服务
func stopHttpServer() error {
	defer func() {
		close(httpServerStopped)
	}()
	logrus.WithFields(logrus.Fields{"location": "stop", "method": "stopHttpServer"}).Info("Shutting down http server...")
	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
	defer cancel()
	if err = srv.Shutdown(ctx); err != nil {
		// 关闭失败时，让进程退出，进而强制关闭http服务

		return err
	}
	select {
	case <-ctx.Done():
		logrus.WithFields(logrus.Fields{"location": "stop", "method": "stopHttpServer"}).Info("Timeout of 2 seconds.")
	}
	logrus.WithFields(logrus.Fields{"location": "stop", "method": "stopHttpServer"}).Info("Stopped http server.")
	return nil
}
